<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>损溢管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<script charset="utf-8" src="${pageContext.request.contextPath}/lib/layui-xtree/layui-xtree.js"></script>
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>损溢管理</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-form" style="width: 180px;">
							<input class="layui-input" id="keyword01" style="width: 170px;" placeholder="请选择年月">
						</div>
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增损溢单</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			<!-- <button class="layui-btn layui-btn-blue" onclick="doExportall()"><i class="layui-icon layui-icon-up"></i>导出</button> -->
			<!-- <button class="layui-btn layui-btn-blue" onclick="uploadExcel()"><i class="layui-icon layui-icon-down"></i>导入</button> -->
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	  <table class="layui-hide" id="tableListSub" lay-filter="tableListSub"></table>
	</div>
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
	</script>

	<!-- 导入框 -->
	<div id="importDiv" hidden="hidden">
		<form class="layui-form" id="uploadform">
			<div style="margin: 20px 0 20px 140px;">
				<input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
			</div>
		</form>
		<button class="layui-btn layui-btn-blue" lay-filter="uplodeform" style="margin-left: 80px">导入数据</button>&emsp;&emsp;&emsp;&emsp;
		<button type="button" class="layui-btn" id="downloadFile">下载模板</button>
	</div>
	
	
	<!-- 新增表单 -->
	 <div id="addDivID" hidden>
		<form class="layui-form" id="addFormID">
			<xblock>
				<table >
					<tr>
						<td><label class="layui-form-label">盘点单号</label></td>
						<td>
							<div style="width: 184px; float: left;">
								<select id="inventory_order" name="inventory_order" lay-verify="inventory_order" lay-filter="inventory_order" style="width: 184px">
									<option value="">请选择盘点单号</option>
									<c:forEach items="${allInventory }" var="inventory">
										<option value="${inventory.inventory_order_num}">${inventory.inventory_order_num }</option>
									</c:forEach>
								</select>
							</div>
							
						</td>
					<tr style="height: 10px"></tr>
				</table>
			</xblock>
			<table class="layui-table" id="myTable">
				<thead style="text-align: center">
					<tr style="background: #009688; color: white">
					<th style="display:none">详情ID</th>
						<th style="display:none" >物料ID</th>
						<th style="text-align:center;">供应商名称</th>
						<th style="text-align:center;">库区名称</th>
						<th style="text-align:center;">物料名称</th>
                   		<th style="text-align:center;">物料编号</th>
						<th style="text-align:center;">物料规格</th>
						<th style="text-align:center;">物料型号</th>
						<th style="text-align:center;">差异数量</th>
						<th style="text-align:center;">损益类型</th>
						<th style="text-align:center;">差异原因</th>
					</tr>
				</thead>
				<tbody id="tbody" style="text-align: center;"></tbody>
			</table>
			<table style="margin-left: 190px">
				<tr>
					<td><label class="layui-form-label"><span>审&nbsp;批&nbsp;人</span></label></td>
					<td style="width:250px; border:1px solid #DBDBDB; margin-top: 10px; overflow: auto;">
						<div id="xtree1"></div>
					</td>
					<td class="layui-hide"><label class="layui-form-label">抄&nbsp;送&nbsp;人</label></td>
					<td class="layui-hide" style="width:250px; height: 200px; border:1px solid #DBDBDB; margin-top: 10px; overflow: auto;">
						<div id="xtree2"></div>
					</td>
					<td colspan="2">
						<input class="layui-hide" lay-verify="approval_id"  lay-filter="approval_id" id="approval_id" name="approval_id" style="width: 206px">
					</td>
					<td class="layui-hide" colspan="2">
					<input class="layui-hide" lay-verify="copy_id" lay-filter="copy_id" id="copy_id" name="copy_id" style="width: 206px">
					</td>
				</tr>
			</table>
			<br>
			<xblock>
				<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:410px; margin-top:10px">提交</button>
				&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-primary" style="margin-top:10px">取消</button>
			</xblock>
		</form>
      </div>
      
 
      <div id="addDivID1" hidden>
			<form class="layui-form" id="addFormID1">
			<xblock>
				<table>
				<tr><label class="layui-form-label">差异原因:</label></tr>
				<tr><textarea id="reason" rows="5" cols="50"  ></textarea></tr>
				</table>
			</xblock>
			<xblock>
				<button class="layui-btn layui-btn-blue" id="subBtn1" lay-submit lay-filter="subForm1" style="margin-left:200px; margin-top:10px; margin-bottom: 10px">提交</button>
				&emsp;&emsp;&emsp;&emsp;<button id="rejectBtn" lay-submit lay-filter="rejectForm" class="layui-btn layui-btn-danger" style="margin-top:10px; margin-bottom: 10px">返回</button>
			</xblock> 	
			</form>
      </div>
	
	
  <script type="text/html" id="rowTo">
        <a class="layui-btn layui-btn-xs" lay-event="update"><i class="layui-icon layui-icon-edit"></i>编辑原因</a>
    </script>
	<script type="text/javascript">
		
		var approvalName = "";
		var copyName = "";
		var inventoryOrderId;
		
        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $("#keyword").val();
					table.reload('contenttable',{
						method:'get',
						where:{"keyword01":keyword01}
						,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
				}
			}
			
			table.render({
				elem: '#tableList'
				,url:'${pageContext.request.contextPath }/lossSpillover/queryLossSpilloverCriteria.do'
				,toolbar: '#toolbar'
				,title: '损溢管理'
				,id :'contenttable'
				,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
				,cols: [[
				  {type: 'checkbox', fixed: 'left', },
				  {field:'', title:'序号', width: 50, /* sort: true,  */type:'numbers', align:'center'},
				  {field:'inventory_order', title:'盘点单', align:'center'},
				  {field:'loss_spillover_order', title:'损益单单号', align:'center'},
				  // {field:'loss_spillover_type', title:'损溢类型', align:'center'},
				  {field:'approval_name', title:'审批人名称', align:'center'},
				  {field:'approval_static', title:'状态', align:'center'
					  ,templet: function(d){
					        if(d.approval_status == "0"){
					        	//$('#sh').attr('class','layui-btn layui-btn-danger layui-btn-xs');
					        	return "审批中";
					        }else if(d.approval_status == "1"){
					        	//$('#bsh').attr('class','layui-btn layui-btn-primary layui-btn-xs layui-disabled');
					        	return "审批通过";
					        }else{
					        	//$('#bsh').attr('class','layui-btn layui-btn-primary layui-btn-xs layui-disabled');
					       		return "审批驳回";
					        }
					      }  
				  },
				 /*  {field:'copy_name', title:'抄送人名称', align:'center'}, */
				  {field:'createrName', title:'创建人', align:'center'},
				  {field:'creater_date', title:'创建时间', align:'center'},
				  //{fixed:'right', unresize: true, title:'操作', toolbar: '#rowToolbar', align:'center',width: 100}
				]]
				,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                        
                    })
                }
			});
			laydate.render({
				elem: '#keyword01',
			});
            
			//监听行工具事件
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				
				//alert(data.id)
				var idArr = new Array();
				//单个删除
				if(obj.event === 'del'){
				  layer.confirm('确定删除吗？', function(index){
					var id = obj.data.id;
					idArr[0] = id;
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/lossSpillover/deleteLossSpilloverById.do',
						data:{ "idArr" : idArr },
						success:function(data){
							if(data > 0){
								toastrStyle();
								toastr.success("删除成功！");
								setTimeout(function(){
									location.reload();
								},1000);
								/*setTimeout(function(){
									//关闭模态框
									//父页面刷新
									window.location.reload();
								},2000);*/
							}else{
								toastrStyle();
								toastr.warning("删除失败！");
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					});
					layer.close(index);
				  });
				}
			});
			//监听行工具事件
			table.on('tool(tableListSub)', function(obj){
				var data = obj.data;
		
				var idArr = new Array();
				id = data.id;
					if(data.approval_status == "2"){
					
						layer.open({
	                   	 	type: 1 					//Page层类型
	                    	,area: ['550px', ''] 	//宽  高
	                    	,title: '编辑'
	                   	 	,shade: 0.6 				//遮罩透明度
	                   		,maxmin: true 				//允许全屏最小化
	                   		,anim: 1 					//0-6的动画形式，-1不开启
	                    	,content: $('#addDivID1')
	                    	,success: function(){
	                        	laydate.render({
	                            	elem: '#creater_date'
	                        	});
	                        	form.render();
	                    	}
	                	});
					}
				
				
			});
			
			/**
			 *	选择盘点单后的操作
			 */
			form.on('select()', function(data){
				inventoryOrderId = data.value;
				if(data.value =="-1"){
					$("#materialName").empty();
					$("#materialName").append("<option value='-1'>请先选择盘点单</option>");
					$("#inventory_different").val("");
					$("#materialNumber").val(""); 
				}else{
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailByOrder.do',
						data:{ "orderId" : data.value },
						dataType:'JSON',
						async:false,
						success:function(data){
							$("#materialName").empty(); 
							$("#materialName").append("<option value='-1'>请选择物料名称</option>");
							for(var i = 0 ;i<data.length;i++){
								$("#materialName").append("<option value='"+data[i].id+"'>"+data[i].materiel_name+"</option>");
							} 
						}
					});
				}
				form.render();
			});	
			/**
			 * 添加弹框中，选择物料后，点提交，带回的操作
			 */
				form.on('submit(productform)', function (data) {
					var checkStatus = table.checkStatus('detailTable')
		      		var data = checkStatus.data;
					var b;
					for (var i = 0; i < data.length; i++) {
						console.log("************"+data[i].id)
						var m = data[i].id == null?"":data[i].id;
		               	$("#myTable").find("tr").each(function(){
	                       var tdArr = $(this).children();
	                       var h = tdArr.eq(0).text();
	                       if(h==m){
	                       	 b=0;
	                       	//toastr.warning("记录已经存在，不能重复添加")
	                        }
		               	})
					 }
                     if(b!=0){
                  		var checkStatus = table.checkStatus('detailTable')
      		      		var data = checkStatus.data;
                  		for (var i = 0; i < data.length; i++) {
                 			//console.log("************"+data[i].difference_quantity)
                 			var val01 = data[i].materiel_name == null?"":data[i].materiel_name;
                            var val02 = data[i].materiel_num == null?"":data[i].materiel_num;
                            var val03 = data[i].materiel_size == null?"":data[i].materiel_size;
                            var val04 = data[i].materiel_properties == null?"":data[i].materiel_properties;
                            var val05 = data[i].difference_quantity == null?"":data[i].difference_quantity;
                            var val06 = data[i].materiel_id == null?"":data[i].materiel_id;
                            var val07 = data[i].customer_name == null?"":data[i].customer_name;
                            var val08 = data[i].region_name == null?"":data[i].region_name;
                            var m = data[i].id == null?"":data[i].id;
                           	if(val05<0) {
                          	   var v09='亏损';
                           	} else if (val05>0){
                          		var v09='盈余';
                          	} else if(val05==0){
                              	var v09='正常';
                              	//console.log("*正常**********"+data[i].difference_quantity)
                              }
               				$("#myTable tbody").append('<tr>'+
               					'<td style="display:none">'+m+'</td>'+
               					'<td style="display:none">'+val06+'</td>'+
               					'<td>'+val07+'</td>'+
               					'<td>'+val08+'</td>'+
               					'<td>'+val01+'</td>'+
               					'<td>'+val02+'</td>'+
               					'<td>'+val03+'</td>'+
               					'<td>'+val04+'</td>'+
               					'<td>'+val05+'</td>'+
               					'<td>'+v09+'</td>'+
               					'<td><input type="text" class="layui-input" lay-verify="reason" id="reason"></td>'+
               				'</tr>');
      						}
      		            layer.close(productIndex)
      					return false;
					} else {
                  	//alert("记录已经存在，不能重复添加");	
                  	//setTimeout(function(){
					//location.reload();
					//},1000);
                  	toastrStyle();
                  	toastr.warning("记录已经存在，不能重复添加")
                  	//layer.open(productIndex)
      				return false;
				}
			});
			
			form.on('select(inventory_order)', function(data){
				 var orderid = $('#inventory_order').val();
				 productIndex=layer.open({
		                type: 1 					//Page层类型
		                ,area: ['1000px', '450px'] 	//宽  高
		                ,title: '盘点清单'
		                ,shade: 0.6 				//遮罩透明度
		                ,maxmin: true 				//允许全屏最小化
		                ,anim: 1 					//0-6的动画形式，-1不开启
		                ,content: '<form class="layui-form">' +
									   	'<table id="detailTable" lay-filter="detailTable"></table>' +
									   	'<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>'+
									'</form>'
		                ,success: function () {
		                    table.render({
		                        elem: '#detailTable'
		                        ,url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailByOrder.do?orderId='+orderid
		                        ,cols: [[
		           					{type: 'checkbox', fixed: 'left'}
		           					,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
		           					//,{field:'id', title:'物料ID', align:'center', hide:true} //隐藏不显示
		           					,{field:'customer_name', title:'供应商名称',templet:function(row){
		           						if(row.customer_name!=null){
		           							return row.customer_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'region_name', title:'库区名称',templet:function(row){
		           						if(row.region_name!=null){
		           							return row.region_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_name', title:'物料名称',templet:function(row){
		           						if(row.materiel_name!=null){
		           							return row.materiel_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_num', title:'物料编号',templet:function(row){
		           						if(row.materiel_num!=null){
		           							return row.materiel_num;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_size', title:'物料规格',templet:function(row){
		           						if(row.materiel_size!=null){
		           							return row.materiel_size;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_properties', title:'物料型号',templet:function(row){
		           						if(row.materiel_properties!=null){
		           							return row.materiel_properties;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'difference_quantity', title:'差异数量',templet:function(row){
		           						if(row.difference_quantity!=null){
		           							return row.difference_quantity;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					
		           				]]
		                       ,page:false
		                        ,done : function(){
		                            $('th').css({
		                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                            })
		                        }
		                    });
		                }
		            }); 

				}) 
			
			/**
			 *	选择物料后的操作
			 */
			form.on('select(materialName)', function(data){
				if(data.value =="-1"){
					$("#inventory_different").val("");
					$("#materialNumber").val(""); 
				}else{
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailById.do',
						data:{ "id" : data.value },
						dataType:'JSON',
						async:false,
						success:function(data){
							var json = data.data;
							console.log(json);
							 //$("#inventory_different").val("123");
							for (var i = 0; i < json.length; i++) {
								 $("#inventory_different").val(json[i].difference_quantity);
								 var number = $("#inventory_different").val();
								 if(number > 0){
									 $('#loss_spillover_type').val('盈余');
								 }else if(number < 0){
									 $('#loss_spillover_type').val('亏损');
								 }else{
									 $('#loss_spillover_type').val('正常');
								 }
								 $("#materialNumber").val(json[i].materiel_num); 
							}
							
						}
					});
					
				}
				form.render();
			});

			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			/* form.on('submit(addForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/lossSpillover/addLossSpillover.do',
					data: $("#addFormID").serialize(),
					cache : false,
					type : "post",
					}).done(
						function(res) {
							if (res > 0) {
								toastrStyle();
								toastr.success('添加成功！');
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					).fail(
						function(res) {
							toastrStyle();
							toastr.error('添加失败！');
							setTimeout(function(){
								location.reload();
							},1000);
						}
					)
					return false;
			}); */

			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/lossSpillover/addLossSpillover.do',
					data: $("#addFormID").serialize(),
					cache : false,
					type : "post",
				}).done(
					function(res) {
						if (res > 0) {
							console.log("**"+res);
							//如果父表新增成功再执行新增子表的操作
							$("#tbody tr").each(function(i,dom){
	                            var tr = $(dom).closest("tr");
	                            var tds = tr.find("td");
	                            //主表插入行ID
	                            var loss_id = res;
	                            var difference_quantity = tds.eq(8).html();
	                            var materiel_id = tds.eq(1).html();
	                            var reason=tds.eq(10).find("#reason").val();
	                            var type=tds.eq(9).html();
	                            console.log("**原因"+reason);
	                            $.ajax({
	                                type:'post'
	                                ,url:'${pageContext.request.contextPath}/lossSpillover/addLossDetail.do'
	                                ,data:{"loss_spillover_id":loss_id,  "difference_quantity":difference_quantity,
	                                	"mid":materiel_id,"reason":reason,"type":type}
	                                ,dataType:'json'
	                                ,success:function(data){
	                                    console.log(data);
	                                }
	                            })
                        	});
							/* —————————————— */
							toastrStyle();
							toastr.success('新增成功！');
							setTimeout(function(){
								location.reload();
							},1000);
							/* —————————————— */
						}
					}
				).fail(
					function(res) {
						toastrStyle();
						toastr.error('新增失败！');
						setTimeout(function(){
							location.reload();
						},1000);
					}
				)
				return false;
			});
			
				form.on('submit(subForm1)', function (data) {
					
				  	$.ajax({
						url : '${pageContext.request.contextPath}/lossSpillover/upLossDetail.do',
						data: {id:id,reason:$("#reason").val()},
						cache : false,
						type : "post",
						}).done(
							function(res) {
								if (res > 0) {
									toastrStyle();
									toastr.success('修改完成！');
									setTimeout(function(){
										location.reload();
									},1000);
								}
							}
						).fail(
							function(res) {
								toastrStyle();
								toastr.error('修改失败！');
								setTimeout(function(){
									location.reload();
								},1000);
							}
						)  
						return false;
				});
				
				
			/**
			 * 新增表单校验
			 */
			form.verify({
				
			
				//value：表单的值item：表单的DOM对象
				reason: function(value, item){
					if(value == ''){
						return '差异原因不能为空';
					}
				},
				/* copy_id: function(value, item){
					if(value == ''){
						return '请选择至少一个抄送人';
					}
				}, */
				inventory_order: function(value, item){
					if(value == '-1'){
						return '请选择物料单';
					}
				},
				approval_id: function(value, item){
					if(value == ''){
						return '请选择至少一个审批人';
					}
				},
				materialName: function(value, item){
					if(value == '-1'){
						return '物料名称字段不能为空';
					}
				},
				loss_spillover_type: function(value, item){
					if(value == '0'){
						return '请选择损溢类型';
					}
				}
				
				
			});

			laydate.render({
                elem: '#creater_date'
            });
			
			//增加
            $("#add").click(function(){
                layer.open({
                    type: 1 							//Page层类型
                    ,area: ['1080px', ''] 				//宽  高
                    ,title: '新增'
                    ,shade: 0.6 						//遮罩透明度
                    ,maxmin: true 						//允许全屏最小化
                    ,anim: 1 							//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,success: function(){
                    	var xtree1 = new layuiXtree({
             		       elem: 'xtree1'               //必填
             		       , form: form                 //必填
             		       , data: '${pageContext.request.contextPath}/dept/getDeptXtree.do'
             		       , isopen: false  			//加载完毕后的展开状态，默认值：true
             		       , ckall: true    			//启用全选功能，默认值：false
             		       , ckallback: function () {
             		    		var xtreeArr = new Array();
            		    	   	xtreeArr = xtree1.GetChecked();
            		       		apapprovalName = "";
            		    	  	for (var i = 0; i < xtreeArr.length; i++) {
            		    			apapprovalName+=xtreeArr[i].value+",";
								}
            		           	console.log("sheng1=" + apapprovalName); //开关value值，也可以通过data.elem.value得到
            		           	$("#approval_id").val(apapprovalName);
             		       } 
             		       //全选框状态改变后执行的回调函数
             		       , icon: {        			//三种图标样式，更改几个都可以，用的是layui的图标
             		           open: "&#xe625;"       	//节点打开的图标
             		           , close: "&#xe623;"    	//节点关闭的图标
             		           , end: "&#xe623;"      	//末尾节点的图标
             		       }
             		       , color: {       			//三种图标颜色，独立配色，更改几个都可以
             		           open: "#EE9A00"        	//节点图标打开的颜色
             		           , close: "#EEC591"     	//节点图标关闭的颜色
             		           , end: "#828282"       	//末级节点图标的颜色
             		       }
             		       , click: function (data) {  				
             		    	   	//节点选中状态改变事件监听，全选框有自己的监听事件
             		    		var xtreeArr = new Array();
             		    	   	xtreeArr = xtree1.GetChecked();
             		       		apapprovalName = "";
             		       		//console.log(xtreeArr)
             		    	  	for (var i = 0; i < xtreeArr.length; i++) {
             		    			apapprovalName+=xtreeArr[i].value+",";
								}
             		    	  	console.log("sheng2=" + apapprovalName);
             		           	//开关value值，也可以通过data.elem.value得到
             		           	$("#approval_id").val(apapprovalName);
             		           	//console.log(data.othis); 			//得到美化后的DOM对象
             		       }
             			});
                    	
                    	
                    	var xtree2 = new layuiXtree({
              		       elem: 'xtree2'               //必填
              		       , form: form                 //必填
              		       , data: '${pageContext.request.contextPath}/dept/getDeptXtree.do'
              		       , isopen: false  			//加载完毕后的展开状态，默认值：true
              		       , ckall: true    			//启用全选功能，默认值：false
              		       , ckallback: function () {
              		    	var xtreeArr = new Array();
           		    	 	xtreeArr = xtree2.GetChecked();
           		       		copyName = "";
           		    	  	for (var i = 0; i < xtreeArr.length; i++) {
           		    		    copyName+=xtreeArr[i].value+",";
							}
           		    		copyName=copyName.slice(0,copyName.length-1)
           					console.log("copy"+copyName); 			//开关value值，也可以通过data.elem.value得到
           		           	$("#copy_id").val(copyName);
              		    	   
              		       } //全选框状态改变后执行的回调函数
              		       , icon: {        			//三种图标样式，更改几个都可以，用的是layui的图标
              		           open: "&#xe625;"       	//节点打开的图标
              		           , close: "&#xe623;"    	//节点关闭的图标
              		           , end: "&#xe623;"      	//末尾节点的图标
              		       }
              		       , color: {       			//三种图标颜色，独立配色，更改几个都可以
              		           open: "#EE9A00"        	//节点图标打开的颜色
              		           , close: "#EEC591"     	//节点图标关闭的颜色
              		           , end: "#828282"       	//末级节点图标的颜色
              		       }
              		       , click: function (data) {  //节点选中状态改变事件监听，全选框有自己的监听事件
              		    	 var xtreeArr = new Array();
              		    	   xtreeArr = xtree2.GetChecked();
              		       		copyName = "";
              		    	
              		    	  for (var i = 0; i < xtreeArr.length; i++) {
              		    		    copyName+=xtreeArr[i].value+",";
								}
              		    	copyName=copyName.slice(0,copyName.length-1)
              					console.log("copy"+copyName); 			//开关value值，也可以通过data.elem.value得到
              		           $("#copy_id").val(copyName);
              		           //console.log(data.othis); 			//得到美化后的DOM对象
              		       }
              			}); 
                     	
                    	
                        laydate.render({
                            elem: '#creater_date'
                        });
                        form.render();
                    }
                });
			});
          //行单击事件
            table.on('row(tableList)', function(obj) {
                var data = obj.data;
                console.log(data.id);
                
           
                table.render({
                    elem: '#tableListSub'
                    ,url:'${pageContext.request.contextPath }/lossSpillover/queryLossDetail.do?lossid='+data.id
                    ,toolbar: '#toolbar'
                    ,title: 'machineList'
                    //,id :'contenttable'
                    ,limits:[10,20,30]
                    ,defaultToolbar:['filter', 'print']
                    ,cols: [[
                        //{type: 'checkbox', fixed: 'left'},
                        {field:'id', title:'序号', width: 100, fixed: 'left', unresize: true, sort: true, type:'numbers'},
                        {field:'customer_name', title:'供应商名称', align:'center'}, //隐藏不显示
                        {field:'region_name', title:'库区名称', align:'center'}, //隐藏不显
                        //{field:'customer_name', title:'供应商名称', align:'center'},
                        {field:'materiel_id', title:'物料ID', align:'center', hide:true}, //隐藏不显示
                        {field:'materiel_name', title:'物料名称', align:'center'},
                        {field:'materiel_num', title:'SAP/QAD', align:'center'},
                        {field:'materiel_size', title:'物料规格', align:'center'},
                        {field:'materiel_properties', title:'物料型号', align:'center'},
                        
						{field:'difference_quantity', title:'差异数量', align:'center'},
						{field:'type', title:'损益类型', align:'center'},
						{field:'reason', title:'差异原因', align:'center'	},
						/* {fixed:'right', title:'操作', width:100, align: 'center',
							templet:function(row){
           						if(row.approval_status=='2'){
           							return  '<a class="layui-btn layui-btn-xs" lay-event="update"><i class="layui-icon layui-icon-edit"></i>编辑原因</a>';
           						}else{
           							return "";
           						}
           					}}  */
                    ]]
                    ,page: true
                    ,done : function(){
                        $('th').css({
                            'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                        })
                    }
                });
            });
			//批量删除
			$("#dels").click(function(){
				var rowData = table.checkStatus('contenttable');
				var data = rowData.data;
				var b;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				}else{
					var sum = 0;
					for (var i = 0; i < data.length; i++) {
						console.log("************"+data[i].approval_status)
						if(data[i].approval_status != "2"){
							console.log("**********"+data.approval_status)
							sum += 1;
						}
					}
					if(sum > 0){
						toastrStyle();
						toastr.warning("只能删除审批驳回的记录！");
					}else{
						for(var i=0;i < data.length;i++){
							idArr[i] = data[i].id;
						}
						$.ajax({
							type:'post',
							url:'${pageContext.request.contextPath }/lossSpillover/deleteLossSpilloverById.do',
							data:{"idArr" : idArr},
							success:function(data){
								layer.confirm('确定删除吗？', function(index){
									if(data > 0){
										toastrStyle();
										toastr.success("删除成功！");
										setTimeout(function(){
											location.reload();
										},1000);
										setTimeout(function(){
											//使用setTimeout（）方法设定定时2000毫秒
											//关闭模态框
											//父页面刷新
											window.location.reload();
										},2000);
									}else{
										toastrStyle();
										toastr.warning("删除失败！");
										location.reload();
									}
								});
							}
						});
					}
				}
			});

			//"损溢单"的行内编辑事件
			table.on('edit(tableListSub)', function(obj){ 
				
				 layer.open({
		                type: 1 					//Page层类型
		                ,area: ['670px', '330px'] 	//宽  高
		                ,title: '编辑 '
		                ,shade: 0.6 				//遮罩透明度
		                ,maxmin: true 				//允许全屏最小化
		                ,anim: 1 					//0-6的动画形式，-1不开启
		                ,content: $('#addDivID1')
		                    
		                ,success: function(){
		                    laydate.render({
		                        elem: '#oildate'
		                    });
		                    form.render();
		                }
		            });
			});
			/**
			 * 获取选中产品列表,将数据添加到弹框表格
			 */
			var rowDatas = null;
			table.on('checkbox(materielTable)', function(obj){
				if(obj.checked){
					rowDatas = obj.data;
					
                    var val01 = rowDatas.materiel_name == null?"":rowDatas.materiel_name;
                    var val02 = rowDatas.materiel_num == null?"":rowDatas.materiel_num;
                    var val03 = rowDatas.materiel_size == null?"":rowDatas.materiel_size;
                    
                    var val04 = rowDatas.materiel_properties == null?"":rowDatas.materiel_properties;

					$("#myTable tbody").append('<tr id="'+obj.tr.get(0)+'">'+
						'<td>'+val01+'</td>'+
						'<td>'+val02+'</td>'+
						
						'<td>'+val03+'</td>'+
						'<td>'+val04+'</td>'+
						'<td>'+0+'</td>'+
					'</tr>');
				} else {
					$("#"+obj.tr.get(0)).remove();
				}
			});

			form.on('select(customer_id)', function(data){
			 var customerId = $('#customer_id').val();
			layer.open({
	                type: 1 					//Page层类型
	                ,area: ['900px', '450px'] 	//宽  高
	                ,title: '物料清单'
	                ,shade: 0.6 				//遮罩透明度
	                ,maxmin: true 				//允许全屏最小化
	                ,anim: 1 					//0-6的动画形式，-1不开启
	                ,content: '<form class="layui-form">' +
								   	'<table id="materielTable" lay-filter="materielTable"></table>' +
								   	
							  '</form>'
	                ,success: function () {
	                    table.render({
	                        elem: '#materielTable'
	                        ,url:'${pageContext.request.contextPath }/lossSpillover/listMaterielByCustomerId.do?cid='+customerId
	                        
	                        ,defaultToolbar:['filter', 'print']
	                        ,cols: [[
	           					{type: 'checkbox', fixed: 'left'}
	           					,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
	           					//,{field:'id', title:'物料ID', align:'center', hide:true} //隐藏不显示
	           					,{field:'materiel_name', title:'物料名称',templet:function(row){
	           						if(row.materiel_name!=null){
	           							return row.materiel_name;
	           						}else{
	           							return "";
	           						}
	           					}}
	           					,{field:'materiel_num', title:'物料编号',templet:function(row){
	           						if(row.materiel_num!=null){
	           							return row.materiel_num;
	           						}else{
	           							return "";
	           						}
	           					}}
	           					,{field:'materiel_size', title:'物料规格',templet:function(row){
	           						if(row.materiel_size!=null){
	           							return row.materiel_size;
	           						}else{
	           							return "";
	           						}
	           					}}
	           					,{field:'materiel_properties', title:'物料型号',templet:function(row){
	           						if(row.materiel_properties!=null){
	           							return row.materiel_properties;
	           						}else{
	           							return "";
	           						}
	           					}}
	           					
	           				]]
	                        ,page: false
	                        ,done : function(){
	                            $('th').css({
	                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                            })
	                        }
	                    });
	                }
	            }); 

			})
		});
		
		

		 $(document).on('click','#biyy',function(){
			 alert()
				$('#addDivID1').show()
		});
	</script>
</body>
</html>
